package edu.zju.gis.cky.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class CmdHelper implements Runnable {

    private final String command;
    private final boolean isPrint;

    public CmdHelper(String command, boolean isPrint) {
        this.command = command;
        this.isPrint = isPrint;
    }

    @Override
    public void run() {
        Process process;
        try {
            process = Runtime.getRuntime().exec(this.command);
            new RedirCmdStreamThread(process.getInputStream(), isPrint).start();
            new RedirCmdStreamThread(process.getErrorStream(), isPrint).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class RedirCmdStreamThread extends Thread {
        InputStream is;
        boolean isPrint;

        RedirCmdStreamThread(InputStream is, boolean isPrint) {
            this.is = is;
            this.isPrint = isPrint;
        }

        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    if (isPrint) {
                        System.out.println(">" + line);
                    }
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

}
